package com.atguigu.schedule.config;

import com.atguigu.schedule.service.AutoRecordingService;
import com.atguigu.schedule.service.SrsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 应用启动时自动开始录制
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AutoRecordingStartup implements ApplicationRunner {
    
    private final AutoRecordingService autoRecordingService;
    private final SrsService srsService;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("🚀 应用启动，检查是否需要启动自动录制...");
        
        // 延迟5秒启动，确保SRS服务已就绪
        Thread.sleep(5000);
        
        // 检查SRS服务状态
        boolean srsStatus = srsService.checkSrsStatus();
        log.info("SRS服务状态检查结果: {}", srsStatus);
        if (!srsStatus) {
            log.warn("⚠️ SRS服务不可用，跳过自动录制启动");
            return;
        }
        
        log.info("开始调用startAutoRecording()...");
        // 启动自动录制（使用FFmpeg从SRS拉流录制）
        // 注意：如果SRS已配置DVR自动录制，这里会作为补充录制
        try {
            autoRecordingService.startAutoRecording();
            log.info("startAutoRecording()调用完成");
            // 等待一下，让录制服务有时间启动
            Thread.sleep(2000);
            // 检查录制状态
            Map<String, Object> status = autoRecordingService.getAutoRecordingStatus();
            if (Boolean.TRUE.equals(status.get("isAutoRecording"))) {
                log.info("✅ 自动录制已启动（FFmpeg拉流录制），录制ID: {}", status.get("currentRecordingId"));
            } else {
                log.warn("⚠️ 自动录制启动失败，请检查日志了解详情");
            }
        } catch (Exception e) {
            log.error("❌ 启动自动录制失败: {}", e.getMessage(), e);
            log.warn("💡 提示：如果SRS已配置DVR，推流会自动录制到SRS录制目录");
        }
    }
}

